#!/user/bin/env python3
# -*- coding: utf-8 -*-
"""
--------------------------------------
    Author:     JiChao_Song
    Date  :     2021/12/21 15:50
    Desc  :
--------------------------------------
"""
from bson import ObjectId
from django.core.paginator import Paginator
from django.urls import path
from django.utils.decorators import method_decorator
from django_http_log.common.request import BaseAPIView, MongoBaseAPIView
from django_http_log.common.response import SuccessResponse, SystemExceptionResponse, CommonResponse
from django_http_log.models import Log

from common.decorator.token_decorator import isAuthentication
from common.enums.response_enums import CommonResultEnums
from common.utils.log_utils import logger
from person.serializers.log import RequestLogSerializer
from platform_auth.settings import APIDOC_DECORATOR


class LogsBaseView(MongoBaseAPIView):
    Model = Log

    search_fields = ["path", "-method", "operatorName"]

    queryset = Log.objects.all()

    serializer_class = RequestLogSerializer


class LogsListAPIView(LogsBaseView):
    @APIDOC_DECORATOR.checkParams
    @APIDOC_DECORATOR.start
    @APIDOC_DECORATOR.ApiTag(value = 'log', desc = '日志管理')
    @APIDOC_DECORATOR.ApiOperation(method = 'POST', path = '/log/list', summary = '日志列表')
    @APIDOC_DECORATOR.ApiParams(value = 'pageIndex', type = 'int', require = True, desc = '页码')
    @APIDOC_DECORATOR.ApiParams(value = 'pageSize', type = 'int', require = True, desc = '每页数量')
    @APIDOC_DECORATOR.ApiParams(value = 'path', type = 'string', desc = '接口路径')
    @APIDOC_DECORATOR.ApiParams(value = 'method', type = 'string', desc = '请求方法')
    @APIDOC_DECORATOR.ApiParams(value = 'operatorName', type = 'string', desc = '操作人')
    @method_decorator(isAuthentication(flag = True))
    def post(self, request, *args, **kwargs):
        """
        获取日志列表
        """
        try:
            data = request.data.copy()
            pageIndex, pageSize = data.get('pageIndex'), data.get('pageSize')
            if len(self.search_fields) != 0:
                queryset = self.Model.objects.filter(**self.search_queryset(request))
            else:
                queryset = self.Model.objects.all()

            serializer = self.get_serializer(queryset, many = True)
            pageData = Paginator(serializer.data, pageSize)
            data = {
                'pageCount': pageData.count,
                'pageIndex': pageIndex,
                'pageSize': pageSize,
                'list': pageData.page(pageIndex).object_list
            }
            return SuccessResponse(result = data)

        except Exception as e:
            logger.error(e)
            return SystemExceptionResponse()


class LogsInfoAPIView(LogsBaseView):
    @APIDOC_DECORATOR.checkParams
    @APIDOC_DECORATOR.start
    @APIDOC_DECORATOR.ApiTag(value = 'log', desc = '日志管理')
    @APIDOC_DECORATOR.ApiOperation(method = 'POST', path = '/log/info', summary = '日志详情')
    @APIDOC_DECORATOR.ApiParams(value = 'logId', type = 'string', require = True, desc = '日志id')
    @method_decorator(isAuthentication(flag = True))
    def post(self, request, *args, **kwargs):
        """
        获取日志列表
        """
        try:
            data = request.data.copy()
            logId = ObjectId(data.get('logId'))
            queryset = self.Model.objects.filter(id = logId)
            if queryset.count() == 0:
                return CommonResponse(codeEnums = CommonResultEnums.LOG_NOT_EXITS_BY_ID)
            serializer = self.get_serializer(queryset.first())
            return SuccessResponse(result = serializer.data)

        except Exception as e:
            logger.error(e)

            return SystemExceptionResponse()


urlpatterns = [
    path('list', LogsListAPIView.as_view()),
    path('info', LogsInfoAPIView.as_view()),
]
